package control

import (
	"fmt"
	"github.com/labstack/echo/v4"
	"github.com/zxysilent/utils"
	"time"
	"turingApi/conf"
	"turingApi/model"
)

func SignHandler(c echo.Context) error {
	jcc, err := LoadUser(c)
	if err != nil {
		conf.Logger.Error(fmt.Sprintf("签到异常：%v", err))
		return c.JSON(utils.Fail("加载用户数据失败", err))
	}

	user, has := model.UserGetByOpenid(jcc.OpenId)
	if has {
		sign, has := model.SignGetToday(user.Id)
		if has {
			conf.Logger.Info("今天已经签到" + sign.Created.String())
			return c.JSON(utils.Fail("今日已签到"))
		}
		sl := model.SignLogs{UserId: user.Id, User: user, Created: time.Now()}
		if err := model.SignAdd(&sl); err != nil {
			conf.Logger.Error(fmt.Sprintf("添加签到日志异常：%v", err))
			return c.JSON(utils.Fail("添加签到日志异常", err))
		}
		user.Balance += 3
		if err := model.UserEdit(user, "balance"); err != nil {
			conf.Logger.Error(fmt.Sprintf("更新用户数据失败：%v", err))
			return c.JSON(utils.Fail("更新用户数据失败", err))
		}
		conf.Logger.Info(fmt.Sprintf("签到成功并加3积分"))
		return c.JSON(utils.Succ("succ", user))
	}
	return c.JSON(utils.Fail("用户不存在"))
}
